﻿<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
    EnableViewState="false" UICulture="auto" Inherits="Pages_Reservation_ReservationAdd"
    CodeBehind="ReservationAdd.aspx.cs" %>

<%@ Register Src="~/pages/Reservations/Ascx/ProgramPopup.ascx" TagName="ProgramPopup"
    TagPrefix="uc1" %>
<%@ Register Src="~/pages/Reservations/Ascx/PaymentPopup.ascx" TagName="PaymentPopup"
    TagPrefix="uc2" %>
<%@ Register Src="~/Tools/NumericBox.ascx" TagName="NumericBox" TagPrefix="num" %>
<asp:Content ID="Content1" ContentPlaceHolderID="title" runat="Server">
    Reservation Management
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="using" runat="Server">

    <script type="text/javascript" src="/js/jquery.metadata.js"></script>

    <script type="text/javascript" src="/js/autoNumeric-1.7.4.js"></script>

    <script type="text/javascript" src="/Pages/Reservations/Js/reservation-lib.js"></script>

</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="header" runat="Server">
    <uc1:ProgramPopup ID="ProgramPopup" runat="server" />
    <uc2:PaymentPopup ID="PaymentPopup" runat="server" />
    <a href="Reservation.aspx" title="Back Button"><span id="backbutton">Back</span></a>
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="content" runat="Server">
    <div style="margin: 15px">
        <fieldset style="padding: 10px;">
            <legend>Operator Info </legend>
            <div class="item">
                <div class="label">
                    Booking code:</div>
                <div class="field1">
                    <em>*</em><asp:TextBox ID="txtBookingCode" runat="server" Width="186px" CssClass="required"></asp:TextBox>
                    <asp:Label ID="lblAlert" runat="server" ForeColor="Red">This agent is exist! </asp:Label>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="This field is required."
                        InitialValue="" ControlToValidate="txtBookingCode"></asp:RequiredFieldValidator>
                </div>
            </div>
        </fieldset>
        <fieldset style="padding: 10px;">
            <legend>Contact Information </legend>
            <table>
                <tr>
                    <td colspan="2">
                        <div style="font-size: 10pt; margin: 10px;">
                            <asp:RadioButton ID="radAgent" runat="server" Text="Agent" GroupName="AW"></asp:RadioButton>
                            <asp:RadioButton ID="radWalkIn" runat="server" Text="Walk-In" GroupName="AW" />
                            <asp:HiddenField ID="hdfGuestType" runat="server" />
                        </div>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <div id="divAgent" class="item divAgent" style="display: none;">
                            <div class="label">
                                Agent#:</div>
                            <div class="field">
                                <asp:TextBox ID="txtAgentID" class="tb" runat="server">
                                </asp:TextBox>
                                <asp:HiddenField ID="hdfAgentID" runat="server" />
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <div class="item divAgent" style="display: none;">
                            <div class="label">
                                Company Name:</div>
                            <div class="field">
                                <asp:TextBox ID="txtCompanyName" runat="server"></asp:TextBox>
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <div id="divWalkIn" class="item divWalkIn">
                            <div class="label">
                                Title:</div>
                            <div class="field">
                                <asp:DropDownList ID="ddlTitle" runat="server">
                                    <asp:ListItem>Ms.</asp:ListItem>
                                    <asp:ListItem>Mr.</asp:ListItem>
                                    <asp:ListItem>Mrs.</asp:ListItem>
                                </asp:DropDownList>
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="item">
                            <div class="label">
                                First Name:</div>
                            <div class="field">
                                <asp:TextBox ID="txtFirstName" runat="server" CssClass="required"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="*"
                                    ControlToValidate="txtFirstName"></asp:RequiredFieldValidator>
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="item">
                            <div class="label">
                                Last Name:</div>
                            <div class="field">
                                <asp:TextBox ID="txtLastName" runat="server" CssClass="required"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="*"
                                    ControlToValidate="txtLastName"></asp:RequiredFieldValidator>
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <div class="item">
                            <div class="label">
                                Address Line 1:</div>
                            <div class="field">
                                <asp:TextBox ID="txtAddressLine1" Style="width: 350px" runat="server"></asp:TextBox>
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <div class="item">
                            <div class="label">
                                Address Line 2:</div>
                            <div class="field">
                                <asp:TextBox ID="txtAddressLine2" Style="width: 350px" runat="server"></asp:TextBox></div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="item">
                            <div class="label">
                                Country:</div>
                            <div class="field">
                                <asp:DropDownList ID="ddlCountry" runat="server" AppendDataBoundItems="true">
                                    <asp:ListItem Text="Choose a country ... " Value=""></asp:ListItem>
                                </asp:DropDownList>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*"
                                    InitialValue="" ControlToValidate="ddlCountry"></asp:RequiredFieldValidator>
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="item">
                            <div class="label">
                                City:</div>
                            <div class="field">
                                <asp:TextBox ID="txtCity" runat="server"></asp:TextBox></div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="item">
                            <div class="label">
                                Zip Code:</div>
                            <div class="field">
                                <asp:TextBox ID="txtZipCode" runat="server"></asp:TextBox></div>
                        </div>
                    </td>
                    <td>
                        <div class="item">
                            <div class="label">
                                Email:</div>
                            <div class="field">
                                <asp:TextBox ID="txtEmail" runat="server" CssClass="email"></asp:TextBox>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ErrorMessage="*"
                                    InitialValue="" ControlToValidate="txtEmail"></asp:RequiredFieldValidator>
                                <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="*"
                                    ControlToValidate="txtEmail" ValidationExpression="^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$"></asp:RegularExpressionValidator>
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="item">
                            <div class="label">
                                Tel.:</div>
                            <div class="field">
                                <asp:TextBox ID="txtTel" runat="server"></asp:TextBox>
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="item">
                            <div class="label">
                                Fax:</div>
                            <div class="field">
                                <asp:TextBox ID="txtFax" runat="server"></asp:TextBox>
                            </div>
                        </div>
                    </td>
                </tr>
            </table>
        </fieldset>
        <fieldset style="padding: 10px;">
            <legend class="subtitle">Reservation Info</legend>
            <table>
                <tr>
                    <td>
                        <div class="item">
                            <div class="label">
                                Boat:</div>
                            <div class="field">
                                <asp:Literal ID="LiteralBoat" runat="server"></asp:Literal>
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="item">
                            <div class="label">
                                Booking status:</div>
                            <div class="field">
                                <asp:DropDownList runat="server" ID="ddlBookingStatus">
                                    <asp:ListItem Value="0">In Progress</asp:ListItem>
                                    <asp:ListItem Value="1">Cancelled</asp:ListItem>
                                </asp:DropDownList>
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="item">
                            <div class="label">
                                N&#186; of nights:</div>
                            <div class="field">
                                <asp:Literal ID="LiteralDataNumber" runat="server"></asp:Literal>
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="item">
                            <div class="label">
                                N&#186; of Cabins:</div>
                            <div id="noOfCabins" class="field">
                                <asp:Literal ID="LiteralCabinNumber" runat="server"></asp:Literal>
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="item">
                            <div class="label" style="color: Blue">
                                Departure Date:</div>
                            <div class="field">
                                <asp:Literal ID="LiteralDepartureDate" runat="server"></asp:Literal>
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="item">
                            <div class="label">
                                Board Date:</div>
                            <div class="field">
                                <asp:Literal ID="LiteralCheckInData" runat="server"></asp:Literal>
                            </div>
                        </div>
                    </td>
                </tr>
                <tr>
                    <td>
                        <div class="item">
                            <div class="label" style="color: Red">
                                Alarm:</div>
                            <div class="field">
                                <asp:TextBox ID="txtAlarm" runat="server" CssClass="datepicker"></asp:TextBox>
                            </div>
                        </div>
                    </td>
                    <td>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:TextBox ID="txtNote" runat="server" TextMode="MultiLine" Rows="10" Height="200"
                            Width="510px"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td colspan="2" align="center">
                        <a onclick="javascript:window.scrollTo(0, 20000);" class="button"><span>Go to bottom</span></a>
                    </td>
                </tr>
            </table>
        </fieldset>
        <!-- Cabin information -->
        <fieldset style="padding: 10px;">
            <legend class="subtitle">Cabin Info</legend>
            <asp:Repeater ID="rpt" runat="server" OnItemDataBound="rpt_ItemDataBound">
                <ItemTemplate>
                    <table class="cabinItem">
                        <tr>
                            <td>
                                <div class="item">
                                    <div class="label">
                                        Cabin:</div>
                                    <div class="field">
                                        <asp:TextBox ID="txtCabinNumber" runat="server" Text='<%#Eval("CabinNumber")%>' ReadOnly="true"></asp:TextBox>
                                        <asp:TextBox ID="hdfCabinID" runat="server" Text='<%#Eval("CabinID")%>' Style="display: none"></asp:TextBox>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <div class="item">
                                    <div class="label">
                                        Boat:</div>
                                    <div class="field">
                                        <%#Eval("BoatName")%>
                                        <asp:HiddenField ID="hdfBoatID" runat="server" Value='<%#Eval("BoatID")%>' />
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <div class="item">
                                    <div class="label">
                                        Representative:</div>
                                    <div class="field">
                                        <asp:TextBox ID="txtRepresentative" runat="server"></asp:TextBox>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <div class="item">
                                    <div class="label">
                                        Status:
                                    </div>
                                    <div class="field">
                                        <asp:DropDownList ID="ddlStatus" runat="server" CssClass="ddlStatus">
                                            <asp:ListItem Value="1">Booked</asp:ListItem>
                                            <asp:ListItem Value="2">Blocked</asp:ListItem>
                                            <asp:ListItem Value="3">Release</asp:ListItem>
                                        </asp:DropDownList>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <div class="item">
                                    <div class="label">
                                        Type of cabin:
                                    </div>
                                    <div class="field">
                                        <asp:DropDownList ID="ddlBedrooms" runat="server">
                                            <asp:ListItem Value="1">Double</asp:ListItem>
                                            <asp:ListItem Value="2">Twin</asp:ListItem>
                                            <asp:ListItem Value="3">Single</asp:ListItem>
                                        </asp:DropDownList>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <div class="item">
                                    <div class="label">
                                        Block dates:
                                    </div>
                                    <div class="field">
                                        <asp:DropDownList ID="ddlBlockDates" runat="server">
                                            <asp:ListItem>1</asp:ListItem>
                                            <asp:ListItem>2</asp:ListItem>
                                            <asp:ListItem>3</asp:ListItem>
                                            <asp:ListItem>4</asp:ListItem>
                                            <asp:ListItem>5</asp:ListItem>
                                            <asp:ListItem>6</asp:ListItem>
                                            <asp:ListItem>7</asp:ListItem>
                                            <asp:ListItem>8</asp:ListItem>
                                            <asp:ListItem>9</asp:ListItem>
                                            <asp:ListItem>10</asp:ListItem>
                                            <asp:ListItem>11</asp:ListItem>
                                            <asp:ListItem>12</asp:ListItem>
                                            <asp:ListItem>13</asp:ListItem>
                                            <asp:ListItem>14</asp:ListItem>
                                            <asp:ListItem>15</asp:ListItem>
                                        </asp:DropDownList>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <div class="item">
                                    <div class="label">
                                        Price:</div>
                                    <div class="field">
                                        <asp:TextBox ID="txtPrice" runat="server" Width="100" Text="0" onblur="getBoatingAmount()"></asp:TextBox>
                                        &nbsp
                                    </div>
                                </div>
                            </td>
                            <td>
                                <div class="item">
                                    <div class="label">
                                        # of Pax:</div>
                                    <div class="field">
                                        <asp:DropDownList ID="ddlNumberClient" runat="server" onchange="changeNumOfPax()">
                                            <asp:ListItem>0</asp:ListItem>
                                            <asp:ListItem>1</asp:ListItem>
                                            <asp:ListItem>2</asp:ListItem>
                                            <asp:ListItem>3</asp:ListItem>
                                            <asp:ListItem>4</asp:ListItem>
                                            <asp:ListItem>5</asp:ListItem>
                                            <asp:ListItem>6</asp:ListItem>
                                            <asp:ListItem>7</asp:ListItem>
                                            <asp:ListItem>8</asp:ListItem>
                                            <asp:ListItem>9</asp:ListItem>
                                            <asp:ListItem>10</asp:ListItem>
                                        </asp:DropDownList>
                                    </div>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2">
                                <div class="item">
                                    <div class="label">
                                        Notes:</div>
                                    <div class="field">
                                        <asp:TextBox ID="txtNote" runat="server" TextMode="MultiLine" Height="100" Width="410"></asp:TextBox></div>
                                </div>
                            </td>
                        </tr>
                    </table>
                </ItemTemplate>
            </asp:Repeater>
            <div class="item">
                <div class="label">
                    Email Confirm:</div>
                <div class="field">
                    <asp:TextBox ID="txtEmailConfirmation" runat="server" CssClass="email"></asp:TextBox></div>
            </div>
            <div style="padding-left: 250px">
                <a class="button" id="btnSave" href="javascript:void(0)"><span>Save</span> </a><a
                    class="button" href="javascript:void(0)" title="Save & Confirm" id="btnSaveNConfirm" style="display: none">
                    <span>Save & Confirm</span></a>
                <asp:HiddenField ID="hdfPos" runat="server" />
                <asp:HiddenField ID="hidProgram" runat="server" />
                <asp:HiddenField ID="hidPayment" runat="server" />
            </div>
        </fieldset>
        
        <!-- Payment History -->
        <fieldset style="padding: 10px;">
            <legend class="subtitle">Payment History</legend>
            <!-- Payment List -->
            <div id="divPaymentHistory">
            </div>
        </fieldset>
        <fieldset style="padding: 10px;">
            <table style="float: right; width: 300px; line-height: 30px;" cellspacing="0" cellpadding="0">
                <tbody>
                    <tr>
                        <td>
                            # of pax:
                            <num:NumericBox ID="txtTotalClients" runat="server" CssClass="integer" MaxLength="3"
                                Text="0" />
                        </td>
                        <td>
                            x
                            <asp:CheckBox ID="chkShuttle" runat="server" Text="(Shuttle)" />
                        </td>
                        <td>
                            <num:NumericBox ID="txtShuttlePrice" runat="server" Text="0" />
                        </td>
                    </tr>
                    <tr>
                        <td>
                        </td>
                        <td>
                            Cruise package:
                        </td>
                        <td>
                            <num:NumericBox ID="txtBoatingFee" runat="server" Text="0" />
                        </td>
                    </tr>
                    <tr style="height: 15px">
                        <td>
                        </td>
                        <td colspan="2">
                            <hr />
                        </td>
                    </tr>
                    <tr>
                        <td>
                        </td>
                        <td style="font-size: x-large; font-weight: bolder;">
                            &Sigma;<asp:DropDownList ID="ddlReservationCurrency" runat="server" Width="68px"
                                Font-Bold="true" Style="border: 0">
                            </asp:DropDownList>
                            <asp:HiddenField ID="txtReservationRate" runat="server" Value="1"></asp:HiddenField>
                        </td>
                        <td>
                            <num:NumericBox ID="txtTotal" runat="server" Text="0" Enabled="false" />
                        </td>
                    </tr>
                    <tr style="height: 15px">
                        <td colspan="3">
                            <hr style="border-color: Red" />
                        </td>
                    </tr>
                    <tr>
                        <td>
                        </td>
                        <td>
                            Sub-Total:
                        </td>
                        <td>
                            <num:NumericBox ID="txtSubTotal" runat="server" Text="0" Enabled="false" />
                        </td>
                    </tr>
                    <tr style="color: Red">
                        <td>
                        </td>
                        <td>
                            Deposit:
                        </td>
                        <td>
                            <num:NumericBox ID="txtDeposit" runat="server" Text="0" Enabled="false" />
                        </td>
                    </tr>
                    <tr style="color: Green">
                        <td>
                        </td>
                        <td>
                            Paid:
                        </td>
                        <td>
                            <num:NumericBox ID="txtPaid" runat="server" Text="0" Enabled="false" />
                        </td>
                    </tr>
                    <tr style="color: Gray">
                        <td>
                        </td>
                        <td>
                            Fee:
                        </td>
                        <td>
                            <num:NumericBox ID="txtPaymentFee" runat="server" Text="0" Enabled="false" />
                        </td>
                    </tr>
                    <tr style="color: Blue">
                        <td>
                        </td>
                        <td>
                            Balance:
                        </td>
                        <td>
                            <num:NumericBox ID="txtBalance" runat="server" Text="0" Enabled="false" />
                        </td>
                    </tr>
                </tbody>
            </table>
            <div class="item" style="display: none">
                <div class="label">
                    Payment complete:
                </div>
                <div class="field">
                    <asp:CheckBox ID="chkPaidComplete" runat="server" CssClass="checkbox" />
                </div>
            </div>
            <asp:HiddenField ID="hdfCharterPrice" runat="server" Value="0" />
        </fieldset>
        <p class="back-top">
            <a href="#top"><span></span></a>
        </p>
        <p class="go-bottom">
            <a href="#bottom"><span></span></a>
        </p>
    </div>

    <script type="text/javascript">

        // get exchange rates
        var exchangeRates;

        // Contact information group
        var agentIDCtl = $("#<%=hdfAgentID.ClientID %>"),
            clientTypeCtl = $("#<%=hdfGuestType.ClientID %>"),
            companyNameCtl = $("#<%=txtCompanyName.ClientID %>"),
            firstNameCtl = $("#<%=txtFirstName.ClientID %>"),
            lastNameCtl = $("#<%=txtLastName.ClientID %>"),
            addressLine1 = $("#<%=txtAddressLine1.ClientID %>"),
            addressLine2 = $("#<%=txtAddressLine2.ClientID %>"),
            countryCtl = $("#<%=ddlCountry.ClientID %>"),
            cityCtl = $("#<%=txtCity.ClientID %>"),
            zipCodeCtl = $("#<%=txtZipCode.ClientID %>"),
            emailCtl = $("#<%=txtEmail.ClientID %>"),
            telephoneCtl = $("#<%=txtTel.ClientID %>"),
            faxNumberCtl = $("#<%=txtFax.ClientID %>"),
            radAgentCtl = $("#<%=radAgent.ClientID %>"),
            radWalkInCtl = $("#<%=radWalkIn.ClientID %>"),
        // Reservation controls
            bookingCodeCtl = $("#<%=txtBookingCode.ClientID %>"),
            charterPriceCtl = $("#<%=hdfCharterPrice.ClientID %>"),
            totalClientsCtl = $("#<%=txtTotalClients.ClientID %>"),
        // Payment group
            depositCtl = $("#<%=txtDeposit.ClientID %>"),
            paidCtl = $("#<%=txtPaid.ClientID %>"),
            balanceCtl = $("#<%=txtBalance.ClientID %>"),
            chkCompleteCtl = $("#<%=chkPaidComplete.ClientID %>");

        $(document).ready(function () {

            $("#<%=lblAlert.ClientID %>").hide();

            // Payment popup
            $('#divPaymentHistory').setTemplateURL("/Pages/Reservations/template/paymentHistoryTemplate.htm");
            $('#divPaymentHistory').processTemplate({ "List": [] });

            $("#gridPaymentHistory a.btnNew").button().click(function () {
                addFlag = true;

                $("#payment-dialog").dialog("open");
            });

            clearForm();

            radAgentCtl.change(function () {
                if ($(this).is(':checked')) {
                    clientTypeCtl.val(0);
                    $(".divWalkIn").css('display', 'none');
                    $(".divAgent").css('display', '');
                    clearForm();
                }
            });

            radWalkInCtl.change(function () {
                if ($(this).is(':checked')) {
                    clientTypeCtl.val(1);
                    $(".divAgent").css('display', 'none');
                    $(".divWalkIn").css('display', '');
                    clearForm();
                }
            });

            // Default value
            radAgentCtl.attr("checked", true);
            radAgentCtl.change();

            if ($("#<%=hdfPos.ClientID %>").val() != 0)
                window.scrollTo(0, $("#<%=hdfPos.ClientID %>").val());

            // Blur events   
            bookingCodeCtl.blur(function () {
                if ($(".representative").val() == '') {
                    $(".representative").each(function () {
                        $(this).val(bookingCodeCtl.val());
                    });
                }
            });

            $(".ddlStatus").change(function () {
                var cabinstatus = $('.ddlStatus');
                cabinstatus.each(function () {
                    var index = $(this).attr("selectedIndex");
                    if (index == 2 && $(this).parents(".cabinItem").css("display") != "none") {
                        if (confirm('Are you sure you want to release this cabin?')) {
                            $(this).parents(".cabinItem").css("display", "none");
                            var noOfCabins = $("#noOfCabins").text();
                            noOfCabins--;
                            $("#noOfCabins").text(noOfCabins);
                        }
                    }
                });
            });

            $(".typeofcabin").change(function () {
                var charter = ('<%=IsCharter %>'.toLowerCase() === 'true');
                if (!charter) {
                    var index = $(this).attr("index");
                    GetPrice(index);
                }
            });
        });

        function ClearReservation() {
            totalClientsCtl.autoNumericSet(0);
            shuttlePriceCtl.autoNumericSet(0);
            totalShuttleCtl.autoNumericSet(0);
            serviceFeeCtl.autoNumericSet(0);
            totalAmountCtl.autoNumericSet(0);
            paidCtl.val("0");
            depositCtl.val("0");
            balanceCtl.val("0");
            chkCompleteCtl.removeAttr('checked');
            $("#<%=ddlBookingStatus.ClientID %>").val("0");
            $("#<%=txtAlarm.ClientID %>").val("");

            //detail
            $(".price").val("0");
            $(".typeofcabin").val("1");
            $(".ddlStatus").val("1");
            $(".txtRepresentative").val("");
            $(".ddlBlockDates").val("1");
            $(".txtNote").val("");
            $(".ddlNumberClient").val("0");
        }

        function clearForm() {
            $("#<%=txtAgentID.ClientID %>").val("");
            companyNameCtl.val("");
            firstNameCtl.val("");
            lastNameCtl.val("");
            addressLine1.val("");
            addressLine2.val("");
            countryCtl.val("");
            cityCtl.val("");
            zipCodeCtl.val("");
            emailCtl.val("");
            telephoneCtl.val("");
            faxNumberCtl.val("");
            // ClearReservation();
        }

        $("#<%=ddlReservationCurrency.ClientID %>").change(function () {
            var rate = getRate($("#<%=ddlReservationCurrency.ClientID %> option:selected").text());
            if (rate != null) {
                // set the exchange rate
                $("#<%=txtReservationRate.ClientID %>").val(rate.UnitPrice);
            }

            getTotal();
        });

        function getBoatingAmount() {
            var boatingAmount = $("input.price").sumCruisePackage();
            $("#<%=txtBoatingFee.ClientID %>").autoNumericSet(boatingAmount);

            getTotal();
        }

        function changeNumOfPax() {
            var numOfPax = $("select.numberclient").sumValues();
            totalClientsCtl.val(numOfPax);

            getBoatingAmount();
        }

        /// <summary>
        /// Get price of the agent
        /// </summary>
        function GetPrice(index) {

            var typeOfCabin = $('.typeofcabin-' + index).val();
            var agentId = agentIDCtl.val();
            var numDate = '<%=NoOfNights %>';
            var priceType = 'cabin-price';
            var boatId = '<%=BoatID %>';
            var jsonStr = JSON.stringify(
            {
                 priceType: priceType, 
                 agentID: agentId, 
                 routeNumber: 0,
                 typeOfCabin: typeOfCabin, 
                 numDate: numDate, 
                 boatId: boatId
            });
            $.ajax({
                type: "POST",
                url: "/Get.asmx/GetPrices",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: jsonStr,
                success: function (msg) {
                    $('.price-' + index).val(msg.d);
                    return false;
                },
                error: function () {
                    alert("Error get prices");
                    $('.price-' + index).val(0);
                    return false;
                }
            });

            getBoatingAmount();
        }

        /// <summary>
        /// Auto complete to fetch the agent list
        /// </summary>
        $(".tb").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/Get.asmx/FetchAgentList",
                    data: "{ 'agentid': '" + request.term + "' }",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataFilter: function (data) { return data; },
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                value: item.GuestID,
                                obj: item
                            }
                        }));
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(textStatus);
                    }
                });
            },
            select: function (event, ui) {
                var guest = ui.item.obj;
                agentIDCtl.val(guest.GuestID);
                companyNameCtl.val(guest.CompanyName);
                firstNameCtl.val(guest.FirstName);
                lastNameCtl.val(guest.LastName);
                addressLine1.val(guest.AddressLine1);
                addressLine2.val(guest.AddressLine2);
                countryCtl.val(guest.CountryID);
                cityCtl.val(guest.City);
                zipCodeCtl.val(guest.ZipCode);
                emailCtl.val(guest.Email);
                telephoneCtl.val(guest.Tel);
                faxNumberCtl.val(guest.Fax);

                $.ajax({
                    type: "POST",
                    url: "/Get.asmx/GetShuttleAndCharter",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: "{ agentID: '" + guest.GuestID + "', boatID: '" + '<%=BoatID %>' + "' }",
                    success: function (data) {
                        if (data.d == null) return false;
                        shuttlePriceCtl.autoNumericSet(data.d.ShuttlePrice);
                        var numOfNights = '<%=NoOfNights %>';
                        var isCharter = '<%=IsCharter %>';
                        if (isCharter) {
                            var subTotal = data.d.CharterPrice * numOfNights;
                            $("#<%=txtSubTotal.ClientID %>").autoNumericSet(subTotal);
                            //                            $("#<%=txtDeposit.ClientID %>").val(data.d.CharterPrice * numOfNights);
                            $("#<%=hdfCharterPrice.ClientID %>").val(subTotal);
                            $("#<%=txtBalance.ClientID %>").autoNumericSet(subTotal);
                        }
                        else {
                            $("#<%=hdfCharterPrice.ClientID %>").val(0);
                        }

                        return false;
                    },
                    error: function () {
                        alert("Error fetch agent.");
                        shuttlePriceCtl.val(0);
                        return false;
                    }
                });

                // Reset price and payment
                $("#<%=txtSubTotal.ClientID %>").autoNumericSet(0);
                $("#<%=txtDeposit.ClientID %>").autoNumericSet(0);
                $("#<%=txtPaymentFee.ClientID %>").autoNumericSet(0);
                $("#<%=txtBalance.ClientID %>").autoNumericSet(0);
            },
            minLength: 1
        });

        /// <summary>
        /// auto complete to get the cabin list
        /// </summary>
        $(".cabinnumber").autocomplete({
            source: function (request, response) {
                var cabins = '';
                var cabinid = $(".cabinid");
                cabinid.each(function () {
                    cabins += ',' + $(this).val();
                });

                var params = "{ boatID: '" + '<%=BoatID %>' + "', boardDateString: '" + '<%=BoardDate %>' + "', noOfNights: " + '<%=NoOfNights %>' + ", cabins: '" + cabins + "' }";

                $.ajax({
                    url: "/Get.asmx/GetAvailableCabins",
                    data: params,
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataFilter: function (data) { return data; },
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                value: item.CabinNumber,
                                obj: item
                            }
                        }));
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        var err = eval("(" + XMLHttpRequest.responseText + ")");
                        alert(err.Message);
                    }
                });
            },
            select: function (event, ui) {
                var index = $(this).attr("index");
                $(".cabinid-" + index).val(ui.item.obj.CabinID);
            },
            minLength: 1
        });

        /// <summary>
        /// Get the customer info to insert to db
        /// </summary>
        function getGuest() {
            var item;
            var guestType = $("#<%=radAgent.ClientID %>").is(':checked') ? 0 : 1;

            item = {
                GuestID: $("#<%=hdfAgentID.ClientID %>").val(),
                AddressLine1: $("#<%=txtAddressLine1.ClientID %>").val(),
                AddressLine2: $("#<%=txtAddressLine2.ClientID %>").val(),
                City: $("#<%=txtCity.ClientID %>").val(),
                CompanyName: $("#<%=txtCompanyName.ClientID %>").val(),
                CountryID: $("#<%=ddlCountry.ClientID %> option:selected").val(),
                Email: $("#<%=txtEmail.ClientID %>").val(),
                Fax: $("#<%=txtFax.ClientID %>").val(),
                FirstName: $("#<%=txtFirstName.ClientID %>").val(),
                GuestType: guestType,
                Lastname: $("#<%=txtLastName.ClientID %>").val(),
                Tel: $("#<%=txtTel.ClientID %>").val(),
                Title: $("#<%=ddlTitle.ClientID %> option:selected").val(),
                ZipCode: $("#<%=txtZipCode.ClientID %>").val(),
                Active: true
            };
            //            }

            return item;
        }

        /// <summary>
        /// Get the reversation info to insert to db
        /// </summary>
        function getReservarion() {
            var item = {
                Status: parseInt($("#<%=ddlBookingStatus.ClientID %>").val()),
                BoatID: '<%=BoatID %>',
                DepartureDate: '<%=DepartureDate.ToShortDate() %>',
                CheckInDate: '<%=BoardDate.ToShortDate() %>',
                IsCharter: '<%=IsCharter %>'.toLowerCase() == 'true',
                IsShuttle: $("#<%=chkShuttle.ClientID %>").is(":checked"),
                ShuttlePrice: $("#<%=txtShuttlePrice.ClientID %>").autoNumericGet(),
                CruisePackage: $("#<%=txtBoatingFee.ClientID %>").autoNumericGet(),
                CruiseRate: $("#<%=txtReservationRate.ClientID %>").autoNumericGet(),
                CruiseCurrency: parseInt($("#<%=ddlReservationCurrency.ClientID %> option:selected").val()),
                NumOfCabins: parseInt('<%=NoOfCabins %>'),
                NumOfNights: parseInt('<%=NoOfNights %>'),
                NumOfPax: parseInt($("#<%=txtTotalClients.ClientID %>").val()),
                SubTotal: $("#<%=txtSubTotal.ClientID %>").autoNumericGet(),
                Deposit: $("#<%=txtDeposit.ClientID %>").autoNumericGet(),
                Paid: $("#<%=txtPaid.ClientID %>").autoNumericGet(),
                PaidFee: $("#<%=txtPaymentFee.ClientID %>").autoNumericGet(),
                Alarm: $("#<%=txtAlarm.ClientID %>").val(),
                Note: $("#<%=txtNote.ClientID %>").val(),
                PaidStatus: $("#<%=chkPaidComplete.ClientID %>").is(":checked"),
                ReservationCode: $("#<%=txtBookingCode.ClientID %>").val(),
                ConfirmationEmail: $("#<%=txtEmailConfirmation.ClientID %>").val()
            }
            return item;
        }

        /// Declare the validation controls
        var validControl = $([]).add($("#<%=txtBookingCode.ClientID %>"))
                                .add($("#<%=txtFirstName.ClientID %>"))
                                .add($("#<%=txtLastName.ClientID %>"));

        /// <summary>
        /// Validation the controls
        /// </summary>
        function validation() {
            var b = true;
            var first = true;
            validControl.each(function () {
                b &= $(this).valid();
                if (!b && first) {
                    $(this).focus();
                    first = false;
                }
            });
            if (!b) return false;

            if (checkBooking($("#<%=txtBookingCode.ClientID %>").val())) {
                $("#<%=lblAlert.ClientID %>").text("This booking code is exists.");
                $("#<%=lblAlert.ClientID %>").css('display', '');
                return false;
            }

            return true;
        }

        /// <summary>
        /// Get Total
        /// </summary>
        function getTotal() {
            var total = toFloat($("#<%=txtShuttlePrice.ClientID %>").autoNumericGet()) +
                        toFloat($("#<%=txtBoatingFee.ClientID %>").autoNumericGet());

            $("#<%=txtTotal.ClientID %>").autoNumericSet(total);

            getSubTotal();
        }

        /// <summary>
        /// Get Sub total
        /// </summary>
        function getSubTotal() {
            var total = $("#<%=txtTotal.ClientID %>").autoNumericGet();
            var subTotal = total * $("#<%=txtReservationRate.ClientID %>").autoNumericGet();

            $("#<%=txtSubTotal.ClientID %>").autoNumericSet(subTotal);

            var sumDeposit = 0;
            var sumFeeAmount = 0;

            var tbody = $('#gridPaymentHistory > tbody');
            $('tr.special', tbody).each(function () {
                sumDeposit += toFloat($(this).children("td:eq(2)").text());
                sumFeeAmount += toFloat($(this).children("td:eq(3)").text());
            });
            $("#<%=txtDeposit.ClientID %>").autoNumericSet(sumDeposit);
            $("#<%=txtPaymentFee.ClientID %>").autoNumericSet(sumFeeAmount);
            $("#<%=txtBalance.ClientID %>").autoNumericSet(subTotal - sumDeposit);
        }

        $("#btnSave").click(function () { Save('Save'); });
        $("#btnSaveNConfirm").click(function () {

            if ($.trim($('#<%=txtEmailConfirmation.ClientID %>').val()) == '') {
                alert('Please input the Email Confirmation to receive the confirmation mail. Thank you!');
            }
            else
                Save('SaveConfirm');
        });

        /// <summary>
        /// Save function
        /// </summary>
        function Save(state) {

            try {
                if (!validation()) return;

                var updateUrl = '', redirectUrl = '', message = '', params = null;

                var guest = getGuest();
                var paymentBatches = getPaymentBatches();
                var reservation = getReservarion();

                getReservationDetails(reservation);

                var jsonGuest = JSON.stringify(guest);
                var jsonPayment = JSON.stringify(paymentBatches);
                var jsonReservation = JSON.stringify(reservation);
                var email = "'" + $('#<%=txtEmailConfirmation.ClientID %>').val() + "'";

                switch (state) {
                    case 'Save':
                        updateUrl = "/Update.asmx/InsertReservation";
                        redirectUrl = "/Pages/Reservations/ReservationList.aspx";
                        message = "Save the booking failed. Details: ";
                        params = "{ reservation: " + jsonReservation + ", guest: " + jsonGuest + ", paymentBatches: " + jsonPayment + " }";
                        break;
                    case 'SaveConfirm':
                        updateUrl = "/Update.asmx/InsertConfirmReservation";
                        redirectUrl = "/Pages/Reservations/EmailConfirmation.aspx?ReservationID={0}";
                        message = "Save and confirmation the booking failed. Details: ";
                        params = "{ reservation: " + jsonReservation + ", guest: " + jsonGuest + ", paymentBatches: " + jsonPayment + ", email: " + email + " }";
                        break;
                }

                $.ajax({
                    url: updateUrl,
                    data: params,
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    async: false,
                    success: function (data) {
                        result = data.d;
                        if (result)
                            window.location = stringformat(redirectUrl, result.ReservationID);
                        else
                            alert('Insert failed');
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        var err = eval("(" + XMLHttpRequest.responseText + ")");
                        alert(message + err.Message);
                    }
                });
            }
            catch (e) {
                alert(e);
            }
        }
        
    </script>

</asp:Content>
